package com.vehiclemanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vehiclemanagement.entity.FuelCard;
import com.vehiclemanagement.entity.FuelCardRecharge;
import com.vehiclemanagement.mapper.FuelCardMapper;
import com.vehiclemanagement.mapper.FuelCardRechargeMapper;
import com.vehiclemanagement.service.FuelCardRechargeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 加油卡充值记录服务实现类
 */
@Service
public class FuelCardRechargeServiceImpl extends ServiceImpl<FuelCardRechargeMapper, FuelCardRecharge> implements FuelCardRechargeService {

    @Autowired
    private FuelCardRechargeMapper fuelCardRechargeMapper;
    
    @Autowired
    private FuelCardMapper fuelCardMapper;

    @Override
    public IPage<FuelCardRecharge> pageRecharges(Integer current, Integer size, String searchTerm, 
                                               Long fuelCardId, Integer status, 
                                               LocalDateTime startTime, LocalDateTime endTime) {
        // 创建分页对象
        Page<FuelCardRecharge> page = new Page<>(current, size);
        
        // 创建自定义SQL条件
        String whereSql = " r.del_flag = 0 ";
        
        // 添加搜索条件
        if (StringUtils.isNotBlank(searchTerm)) {
            whereSql += " AND (f.card_number LIKE '%" + searchTerm + "%' OR r.operator LIKE '%" + searchTerm + "%') ";
        }
        
        // 添加加油卡ID查询条件
        if (fuelCardId != null) {
            whereSql += " AND r.fuel_card_id = " + fuelCardId;
        }
        
        // 添加状态查询条件
        if (status != null) {
            whereSql += " AND r.status = " + status;
        }
        
        // 添加时间范围查询条件
        if (startTime != null) {
            whereSql += " AND r.recharge_time >= '" + startTime + "'";
        }
        
        if (endTime != null) {
            whereSql += " AND r.recharge_time <= '" + endTime + "'";
        }
        
        // 添加排序
        whereSql += " ORDER BY r.recharge_time DESC";
        
        System.out.println("执行查询SQL条件: " + whereSql);
        
        // 执行查询
        return fuelCardRechargeMapper.selectPageWithInfo(page, whereSql);
    }

    @Override
    public FuelCardRecharge getRechargeById(Long id) {
        return fuelCardRechargeMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addRecharge(FuelCardRecharge recharge) {
        System.out.println("服务层开始添加充值记录: " + recharge);
        
        try {
            // 设置默认值
            if (recharge.getRechargeTime() == null) {
                recharge.setRechargeTime(LocalDateTime.now());
            }
            if (recharge.getCreateTime() == null) {
                recharge.setCreateTime(LocalDateTime.now());
            }
            if (recharge.getUpdateTime() == null) {
                recharge.setUpdateTime(LocalDateTime.now());
            }
            if (recharge.getDelFlag() == null) {
                recharge.setDelFlag(0);
            }
            if (recharge.getStatus() == null) {
                recharge.setStatus(1); // 默认成功
            }
            
            // 先插入充值记录
            int result = fuelCardRechargeMapper.insert(recharge);
            
            // 如果充值成功，更新加油卡余额
            if (result > 0 && recharge.getStatus() == 1) {
                FuelCard fuelCard = fuelCardMapper.selectById(recharge.getFuelCardId());
                if (fuelCard != null) {
                    // 更新余额
                    BigDecimal newBalance = fuelCard.getBalance().add(recharge.getAmount());
                    fuelCard.setBalance(newBalance);
                    fuelCard.setUpdateTime(LocalDateTime.now());
                    
                    fuelCardMapper.updateById(fuelCard);
                    System.out.println("更新加油卡余额成功，卡号: " + fuelCard.getCardNumber() + ", 新余额: " + newBalance);
                }
            }
            
            System.out.println("插入结果: " + result + ", 生成的ID: " + recharge.getId());
            
            return result > 0;
        } catch (Exception e) {
            System.err.println("添加充值记录发生异常: " + e.getMessage());
            e.printStackTrace();
            throw e; // 抛出异常以触发事务回滚
        }
    }

    @Override
    public boolean updateRecharge(FuelCardRecharge recharge) {
        // 更新时间
        recharge.setUpdateTime(LocalDateTime.now());
        
        return fuelCardRechargeMapper.updateById(recharge) > 0;
    }

    @Override
    public boolean deleteRecharge(Long id) {
        // 使用物理删除
        System.out.println("执行物理删除充值记录，ID: " + id);
        
        try {
            // 直接物理删除记录
            int result = fuelCardRechargeMapper.deletePhysically(id);
            System.out.println("物理删除结果: " + result);
            return result > 0;
        } catch (Exception e) {
            System.err.println("删除充值记录时出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public BigDecimal getTotalRechargeAmount(Long fuelCardId) {
        return fuelCardRechargeMapper.getTotalRechargeAmount(fuelCardId);
    }

    @Override
    public List<FuelCardRecharge> getRechargesByFuelCardId(Long fuelCardId) {
        LambdaQueryWrapper<FuelCardRecharge> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FuelCardRecharge::getFuelCardId, fuelCardId)
                  .eq(FuelCardRecharge::getDelFlag, 0)
                  .orderByDesc(FuelCardRecharge::getRechargeTime);
        
        return fuelCardRechargeMapper.selectList(queryWrapper);
    }
} 